﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using B10.Models;
using B10.Helpers;

namespace B10.Controllers
{
    [Authorize(Roles = "Admin")]
    [HandleError]
    public class AdminPanelController : Controller
    {
        private const int pageSize = 3;
        private IDatabaseRepository _db;
        private UserPageManager _userMgr;

        public AdminPanelController(IDatabaseRepository db, UserPageManager userManager)
        {
            this._db = db;
            this._userMgr = userManager;
        }

        public AdminPanelController() : this(new DatabaseRepository(), new UserPageManager()) { }


        //
        // GET: /AdminPanel/

        public ActionResult Index(string categoryName, Categories? category, int? page)
        {
            if (category.HasValue)
            {
                string item = CategoryHelper.GetCategoryName(category.Value);
                if (item != categoryName)
                    return RedirectToAction("Index", new { categoryName = item, category = (int)category.Value, page = page });
            }

            
            var pages = _db.GetAllPages();

            pages = pages.Where(p => p.Status == PageStatus.Published)
                .OrderBy(p => p.PublishDate);
            var paginated = new PaginatedList<UserPage>(pages, page ?? 1, pageSize);
            return View(new PageListViewModel(paginated));
        }

        
        public ActionResult Command(string command, int pageID)
        {
            if (!string.IsNullOrEmpty(command))
            {
                if (command.Equals("Accepted"))
                {
                    this._userMgr.SetPageStatus(pageID, true);
                }
                else if (command.Equals("Deny"))
                {
                  this._userMgr.SetPageStatus(pageID, false);
                }
            }

            var pages = _db.GetAllPages();

            pages = pages.Where(p => p.Status == PageStatus.Published);
            var paginated = new PaginatedList<UserPage>(pages, 1, pageSize);
            return View("Index", new PageListViewModel(paginated));
        }

        
    }
}
